<?php

/**
 * Manage some base actions
 * @author Tuong Tran <tuong.tran@outlook.com>
 */
class SiteController extends Controller {

//    public $layout = 'site';

    public function init() {
	parent::init();
    }

    public function filters() {
	return array(
//	    'accessControl'    // required to enable accessRules
	);
    }

    public function accessRules() {
//	return array(
//	    array('allow', // allow all users to perform 'index' and 'view' actions
//		'actions' => array('index', 'logout', 'sign_up', 'forgot_pass', 'contact', 'error', 'page', 'caching', 'captcha', 'newsletter', 'activekey'),
//		'users' => array('*'),
//	    ),
//	    array('allow',
//		'actions' => array(
//		),
//		'users' => array('@')
//	    ),
//	    array('deny', // deny everybody else
//		'users' => array('*')
//	    )
//	);
    }

    /**
     * Declares class-based actions.
     */
    public function actions() {
	return array(
	    // captcha action renders the CAPTCHA image displayed on the contact page
	    'captcha' => array(
		'class' => 'CCaptchaAction',
		'backColor' => 0xFFFFFF,
	    ),
	    'newsletter' => array(
		'class' => 'application.widgets.newsletter.ANewsletter'
	    )
	);
    }

    /**
     * render home page
     */
    public function actionIndex() {

	$aCat = Category::getListCat();
	$aSort = array();
	foreach ($aCat as $key => $value) {
	    if ($value['order_cat'] !== null) {
		$aSort[$key] = $value['order_cat'];
	    }
	}

	$this->render('index', array('aCat' => $aCat, 'aSort' => $aSort));
    }

    /**
     * render contact page
     */
    public function actionContact() {
	$this->layout = 'site';
	$model = new ContactForm;

	if (isset($_POST['ContactForm'])) {
	    $model->attributes = $_POST['ContactForm'];
	    if ($model->validate()) {
		//
		//save model
		$contactUs = new ContactUs;
		$contactUs->attributes = $model->attributes;

		if ($contactUs->save()) {
		    //send the email to admin
		    EmailHelper::sendContactRequest($model);

		    Yii::app()->user->setFlash('contact', '<div class="alert alert-success">Thank you for contacting us. We will respond to you as soon as possible.</div>');
		}

		$this->refresh();
	    }
	}
	$this->render('contact', array('model' => $model));
    }

    /**
     * This is the action to handle external exceptions.
     */
    public function actionError() {
	if ($error = Yii::app()->errorHandler->error) {
	    if (Yii::app()->request->isAjaxRequest)
		echo $error['message'];
	    else
		$this->render('error', $error);
	}
    }

    /**
     * Displays the contact page
     * @author Tuong Tran <tuong.tran@outlook.com>
     * @return void
     */

    /**
     * render custom layout
     * @param type $alias
     */
    public function actionPage($id) {
	$aPage = Yii::app()->db->createCommand('SELECT * FROM {{pages}} WHERE page_id=' . $id)->queryRow();
	$this->layout = 'site';
	if (count($aPage) < 0)
	    throw new CHttpException(404, 'The requested page does not exist.');
	$this->render('page', array('aPage' => $aPage));
    }

    /**
     * Displays the login page
     */
//    public function actionLogin() {
//	$model = new LoginForm;
//
//	// if it is ajax validation request
//	if (isset($_POST['ajax']) && $_POST['ajax'] === 'login-form') {
//	    echo CActiveForm::validate($model);
//	    Yii::app()->end();
//	}
//
//	// collect user input data
//	if (isset($_POST['LoginForm'])) {
//	    $model->attributes = $_POST['LoginForm'];
//	    // validate user input and redirect to the previous page if valid
//	    if ($model->validate() && $model->login()) {
//		$this->redirect(Yii::app()->user->returnUrl);
//	    }
//	}
//	// display the login form
//	$this->render('login', array('model' => $model));
//    }

    /**
     * Logs out the current user and redirect to homepage.
     */
    public function actionLogout() {
	Yii::app()->user->logout();
	$this->redirect(Yii::app()->homeUrl);
    }

    /**
     * This is the action to Clear Cache
     * From backend when administrator wants to clear all site cache using ccache class.
     * He must call this acction to flush front end cache
     */
    public function actionCaching() {
	if (isset($_POST['key'])) {
	    app()->cache->delete($_POST['key']);
	} else {
	    if (isset($_POST['setting']) && isset($_POST['category'])) {
		settings()->deleteCache($_POST['category']);
	    }
	}
    }

    /**
     * Forgot pass
     */
    public function actionForgot_pass() {
	$this->layout = "site";
	$success = '';
	$error = '';
	if (isset($_POST['submit'])) {
	    if ($_POST['email']) {
//		if (filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
		$model = User();
		$newPass = getRandomKey(15);

		$model = User::model()->find("email='" . $_POST['email'] . "' or username='" . $_POST['email'] . "'");
		if ($model) {
		    $model->password = $newPass;
		    $model->save();
		    $success = 1;

		    $resceipt = array(
			'email' => $model->email,
			'username' => $model->username,
			'pass' => $newPass
		    );
		    EmailHelper::sendForgotPassword($resceipt);
		} else {
		    $error = settings()->get('text_site', 'text_forgot_pass');
		}
//		} else {
//		    $error = "Please enter a valid email.";
//		}
	    } else {
		$error = "Please enter email/username here.";
	    }
	}
	$this->render('forgotpass', array('success' => $success, 'error' => $error));
    }

    public function actionSign_up() {

	//when user login	
	$model = new User();
	// Uncomment the following line if AJAX validation is needed
	if (isset($_POST['ajax']) && $_POST['ajax'] == "singup-form") {
	    $model->attributes = $_POST['User'];
	    echo CActiveForm::validate($model);
	    Yii::app()->end();
	}

	//$model = new User();
	$model->scenario = 'insert';
	$model->gender = User::GENDER_MALE;
	$model->country = "US";
	$success = 0;
	//when user register
	if (isset($_POST['signup'])) {
	    $model->attributes = $_POST['User'];
	    $model->display_name = $_POST['User']['first_name'] . ' ' . $_POST['User']['last_name'];
	    $model->birthdate = $_POST['User']['year'] . '-' . $_POST['User']['month'] . '-' . $_POST['User']['day'];
	    if ($model->validate()) {

		$model->status = User::STATUS_WAITING_ACTIVE;
		if ($model->save()) {
		    $success = 1;
		    if (settings()->get('site', 'active_by_mail')) {
			$activationKey = getRandomKey(20);
			$model->activation_key = $activationKey;

			//send mail to active account
			$receiptContent = array(
			    'name' => $model->username,
			    'activationKey' => $activationKey,
			    'emailReceive' => $model->email
			);
			EmailHelper::sendMailResgistration($receiptContent);
		    } else {
			//send mail for waiting approve			
			$receiptContent = array(
			    'name' => $model->username,
			    'emailReceive' => $model->email,
			    'userId' => $model->user_id
			);
			EmailHelper::sendMailForWaitingApprove($receiptContent);

			//send mail to admin for approving
			EmailHelper::sendToAdminForApprove($receiptContent);
		    }
		}
	    }

	    $model->display_name = '';
	    $model->email = '';
	    $model->re_email = '';
	    $model->password = '';
	    $model->repassword = '';
	}
	$this->render('sign-up', array(
	    'model' => $model,
	    'success' => $success
	));
    }

    /**
     * active user when they click active 
     */
    public function actionActiveKey($key) {
	if ($key) {
	    $aUser = Yii::app()->db->createCommand('SELECT * FROM {{users}} WHERE activation_key="' . $key . '"')->queryRow();
	    Yii::app()->db->createCommand('UPDATE {{users}} SET activation_key="", status=1 WHERE activation_key="' . $key . '"')->execute();
	    Yii::app()->session['activeSuccess'] = 1;

	    /**
	     * send welcom mail
	     */
	    $receiptContent = array(
		'name' => $aUser['username'],
		'emailReceive' => $aUser['email']
	    );
	    EmailHelper::sendMailAfterActiveAccount($receiptContent);
	    $this->redirect(SITE_NAME_URL);
	}
    }

}

